<template>
<div>
  <el-table
    header-row-class-name="base-table-header-v3"
    row-class-name="base-table-row-v3"
    class="service-card-table"
    v-loading="listLoading"
    :data="newData"
    :show-summary="hasTotalColumn"
    :summary-method="getSummaries"
    @cell-mouse-enter="mouseEnter"
    @cell-mouse-leave="mouseLeave"
    border>
    <template slot="empty">
      <BaseListForNoData
        v-show="!listLoading"
        table-type="smallTable"
        :notice-msg="$t('common.base.tip.noData')"
      ></BaseListForNoData>
    </template>
    
    <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
    <el-table-column
      v-for="column in columns"
      :key="column.fieldId"
      :label="column.displayName"
      :prop="column.fieldName"
      show-overflow-tooltip
      :min-width="column.minWidth || '100px'">
      <template slot-scope="scope">
        <!-- start 预计用量 -->
        <template v-if="column.fieldName === 'preNum'">
          <template v-if="!scope.row.editable">
            <span>{{ scope.row[column.fieldName] }}</span>
            <i class="iconfont icon-edit-square" @click="editPreNum(scope.row, scope.$index)" v-if="allowEdit"></i>
          </template>

          <template v-else>
            <input
              type="number"
              v-model="scope.row.preNum"
              @change="handlePreNum(scope.row, scope.$inde)"
              @blur="togglePreNumEditable(scope.row, scope.$index)"
            />
          </template>
        </template>
        <!-- end 预计用量 -->

        <!-- start 单价 -->
        <template v-else-if="column.fieldName === 'salePrice'">
          <template v-if="!scope.row.salePriceEditable">
            <span>{{ scope.row | fmt_salePrice_currency }} </span>
            <i class="iconfont icon-edit-square price-icon" @click.stop="editSalePrice(scope.row, scope.$index)" v-if="editUnitPrice"></i>
          </template>

          <template v-else>
            <input
              type="number"
              :class="internationalGray ? 'sale-price-edit' : 'service-number-input'"
              v-model="scope.row.salePrice"
              @change="handleSalePrice(scope.row, scope.$index)"
            />
            <el-select 
              v-if="internationalGray"
              class='sale-price-select' 
              v-model="scope.row.salePriceCurrency" 
              @change="handleSalePriceCurrency(scope.row, scope.$index)" 
              :placeholder="$t('common.placeholder.select')">
              <el-option
                v-for="item in currencyOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                >
              </el-option>
            </el-select>
          </template>
        </template>
        <!-- end 单价 -->

        <template v-else-if="column.fieldName === 'total'">
          {{ scope.row | fmt_total_currency }} 
        </template>

        <!-- start 操作 -->
        <template v-else-if="column.fieldName === 'action'">
          <el-button
            class="text-danger"
            type="text"
            size="mini"
            @click="deleteService(scope.row, scope.$index)"
          >{{$t('common.base.delete')}}</el-button>
        </template>
        <!-- end 操作 -->

        <template v-else>
          {{ $formatFormField(column, scope.row) }}
        </template>
      </template>
    </el-table-column>
  </el-table>
  
    <!-- 底部数据量统计 -->
    <div class="table-footer">
      <i18n path="common.base.table.totalCount">
        <span place="count" class="level-padding">{{data.length || 0}}</span>
      </i18n>
    </div>
</div>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi';
/* util */
import MathUtil from '@src/util/math';
/* enum */
import { TaskEventNameMappingEnum } from '@model/enum/EventNameMappingEnum.ts';
/* model */
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH } from '@src/model/const/Number';
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH_MESSAGE } from '@src/model/const/Alert';
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()
import { currencyOption } from '@src/util/currency'
export default {
  name: 'service-card-list',
  props: {
    data: {
      type: Array,
      default: () => ([])
    },
    columns: {
      type: Array,
      default: () => ([])
    },
    listLoading: {
      type: Boolean,
      default: false
    },
    allowEdit: {
      type: Boolean,
      default: false
    },
    editUnitPrice: {
      type: Boolean,
      default: false
    },
    internationalGray: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      currencyOption,
      oldIndex: -1,
      index: -1
    }
  },
  computed: {
    newData() {
      return disposeFormListViewTime(this.data, this.columns)
    },
    hasTotalColumn() {
      return this.columns.some(c => c.fieldName == 'total')
    },
    isSameCurreny() {
      if(this.data.length > 0) {
        if(this.data.length == 1) return true
        let salePriceCurrency = this.data[0].salePriceCurrency || 'CNY'
        let flag = this.data.every(item=> item.salePriceCurrency == salePriceCurrency)
        return flag
      }
      return false
    },
    totalCurrency() {
      return this.data[0]?.salePriceCurrency || 'CNY'
    }
  },
  watch: {
    data: {
      immediate: true,
      async handler(){
        // 合并合计列
        await this.$nextTick()
        const tds = document.querySelectorAll('.service-card-table .el-table__footer-wrapper tr>td')
        if (tds.length) {
          tds[0].colSpan = tds.length
          tds.forEach((td, ind) => {
            if (ind != 0) {
              td.display = 'none'
            }
          })
        }
      }
    }
  },
  methods: {
    disposeFormListViewTime,
    mouseEnter(row, column, cell) {
      if(column.property == 'salePrice') {
        const index = this.data.findIndex(item => row.id === item.id)
        this.oldIndex = index 
      }
    },
    mouseLeave(row, column, cell) {
      this.oldIndex = -1
      const index = this.data.findIndex(item => row.id === item.id)
      this.index = index
    },

    cellClickEvent(e) {
      if(!(e.target.className.includes('price-icon'))) {
        if(this.oldIndex >=0 ) return 
        this.newData.forEach(item => {
          this.$set(item, 'salePriceEditable', false);
        })
      }
    },
    /** 
    * @description 删除服务项目
    */
    async deleteService(row, index) {
      let result = await this.$platform.confirm(this.$t('task.tip.deleteTip'));
      if (!result) return;

      TaskApi.deleteByInventory({inventoryId: row.id})
        .then(res => {
          if (res.success) {
            this.$platform.notification({
              type: 'success',
              title: this.$t('common.base.deleteSuccess')
            })

            this.data.splice(index, 1);
            
            this.$eventBus.$emit(TaskEventNameMappingEnum.UpdateRecord);
          } else {
            this.$platform.alert(res.message);
          }
        }).catch(err => console.error(err))
    },

    // 点击编辑单价
    editSalePrice(row, index) {
      // 备份单价数据
      row.oldPrice = row.salePrice;
      if(index !== this.index) {
        this.newData.forEach(item => {
          if(item.index != index) {
            this.$set(item,  'salePriceEditable', false)
          }
        })
      }
      this.toggleSalePriceEditable(row);
    },

    // 修改单价
    handleSalePrice(item) {
      let value = Number(item.salePrice);
      let count = MathUtil.decimalNumber(value);
      let oldPrice = Number(item.oldPrice ? item.oldPrice : 0);

      if(value < 0){
        this.$platform.alert(this.$t('common.currency.exchangeRateLimit3'));
        item.salePrice = oldPrice;
        return;
      }

      if(count > 2) {
        this.$platform.alert(this.$t('common.currency.exchangeRateLimit4'));
        item.salePrice = oldPrice;
        return;
      }

      const payload = {
        id: item.id,
        preNum: item.preNum,
        salePrice: item.salePrice,
        type: 2
      }
      TaskApi.putTaskInventoryValue(payload)
        .then(res => {
          if (res.success) {
            item.oldPrice = item.salePrice;
            item.total = (item.preNum * item.salePrice).toFixed(2);
          } else {
            this.$platform.alert(res.message);
          }
        }).catch(err => console.error(err))
    },
    handleSalePriceCurrency(item) {
      const payload = {
        id: item.id,
        preNum: item.preNum,
        salePrice: item.salePrice,
        salePriceCurrency: item.salePriceCurrency,
        type: 2
      }
      TaskApi.putTaskInventoryValue(payload)
        .then(res => {
          if (res.success) {
            item.total = (item.preNum * item.salePrice).toFixed(2);
          } else {
            this.$platform.alert(res.message);
          }
        }).catch(err => console.error(err))
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (column.property == 'total') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return Number(prev) + Number(curr)
              } else {
                return prev
              }
            }, 0)
            if (this.internationalGray) {
              sums[0] = this.isSameCurreny ? `${this.$t('common.base.amountCount')}: ${sums[index]} ${this.totalCurrency}` : `${this.$t('common.base.amountCount')}: -`
            } else {
              sums[0] = `${this.$t('common.base.amountCount')}: ¥${sums[index]}`
            }
            sums[index] = ''
          } else {
            sums[index] = ''
          }
        } else {
          index == 0 ? '' : sums[index] = ''
        }
      });
      return sums;
    },

    // 更新预计用量是否可编辑状态
    toggleSalePriceEditable(row) {
      this.$set(row, 'salePriceEditable', true);
    },

    /**
    * @description 点击编辑预计用量
    */
    editPreNum(row, index) {
      // 备份预计用量数据
      row.backupNum = row.preNum;

      this.togglePreNumEditable(row, index);
    },
    /**
    * @description 修改预计用量
    */
    handlePreNum(item, index) {
      let value = Number(item.preNum);
      let count = MathUtil.decimalNumber(value);

      if (value <= 0) {
        this.$platform.alert(this.$t('task.tip.rightNumTip'));
        item.preNum = item.backupNum;
        return;
      }

      if (value > PART_SERVICE_LIST_PRENUM_MAX_LENGTH) {
        this.$platform.alert(`${this.$t('common.base.estimate')}${ PART_SERVICE_LIST_PRENUM_MAX_LENGTH_MESSAGE }`);
        item.preNum = item.backupNum;
        return;
      }

      if (count > 2) {
        this.$platform.alert(this.$t('task.tip.twoDigitalTip'));
        item.preNum = item.backupNum;
        return;
      }

      // 去掉多余0
      item.preNum = item.preNum.replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');

      TaskApi.putTaskInventoryValue({id: item.id, preNum: item.preNum, type: 2})
        .then(res => {
          if (res.success) {
            item.backupNum = item.preNum;
            item.total = (item.preNum * item.salePrice).toFixed(2);
          } else {
            this.$platform.alert(res.message);
          }
        }).catch(err => console.error(err))
    },
    /** 
    * @description 更新预计用量是否可编辑状态
    */
    togglePreNumEditable(row, index) {
      this.$set(row, 'editable', !row.editable);
    }
  },
  mounted() {
    window.addEventListener('click', this.cellClickEvent)
  }
}
</script>

<style lang="scss" scoped>
.service-card-table {
  border-top: 1px solid #ebeef5;

  .base-table-row-v3 td {
    .el-button {
      min-width: auto !important;
      padding: 0;
    }
  }

  input[type="number"] {
    width: 99%;
  }
  .sale-price-select {
    width: 45%;
  }
  .service-number-input {
    width: 99%;
  }
  .sale-price-edit {
    width: 55%!important;
  }
  .icon-edit-square {
    margin-left: 8px;
    vertical-align: middle;

    &:hover {
      color: $color-primary;
      cursor: pointer;
    }
  }
}
::v-deep .el-table__footer-wrapper tbody td {
  background-color: #F5F7FA !important;
  border: none;
}
</style>
